package com.a21vianet.quincysx.demo.socket;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    private static final int HANDLER_MASSAGE_TOAST = 1;

    private static final String TAG = MainActivity.class.getSimpleName();

    private EditText mEditText;

    private Socket mClientSocket;
    private PrintWriter mPrintWriter;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_MASSAGE_TOAST:
                    Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEditText = findViewById(R.id.edit_msg);

        Intent intent = new Intent(this, RemoteService.class);
        startService(intent);

        new Thread(new Runnable() {
            @Override
            public void run() {
                connectServiceSocket();
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        if (mClientSocket != null) {
            try {
                mClientSocket.shutdownInput();
                mClientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }

    private void connectServiceSocket() {
        Socket socket = null;
        while (socket == null) {
            try {
                socket = new Socket("localhost", 8895);
                mClientSocket = socket;
                mPrintWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),
                        true);
                Log.e(TAG, "连接成功");
            } catch (IOException e) {
                e.printStackTrace();
                SystemClock.sleep(1000);
            }
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket
                    .getInputStream()));
            while (!MainActivity.this.isFinishing()) {
                String msg = reader.readLine();
                Log.e(TAG, "来自服务端的消息:" + msg);

                Message message = Message.obtain(null, HANDLER_MASSAGE_TOAST);
                message.obj = "来自服务端的消息:" + msg;
                mHandler.sendMessage(message);

            }
            Log.e(TAG, "关闭连接");
            reader.close();
            mPrintWriter.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onClick(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mPrintWriter != null) {
                    String msg = mEditText.getText().toString();
                    mPrintWriter.println(msg);
                    Log.e(TAG, "发送成功:" + msg);

                    Message message = Message.obtain(null, HANDLER_MASSAGE_TOAST);
                    message.obj = "发送成功:" + msg;
                    mHandler.sendMessage(message);
                }
            }
        }).start();
    }
}
